// block tree
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
const startTagClose = /^\s*(\/?)>/
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g


function parseStartTag(text:string) {
  const result = text.match(startTagOpen)!
  const obj = {
    tag: result[1],
    attrs:{},
    children:[]
  }

  let size = result[0].length
  let attr: RegExpMatchArray|null = null

  text = text.substring(size)

  while(!text.match(startTagClose) && (attr=text.match(attribute))) {
    let len = attr[0].length

    Reflect.set(obj.attrs, attr[1], attr[3])

    text = text.substring(len)
    size += len
  }
  
  return [obj, size] as const
}

function parseText(text:string) {}

function parseEndTag(text:string) {
  const result = text.match(startTagClose)

  return result
}


function parseHtmlToAst(tpl:string) {
  while(tpl) {
    const pos = tpl.indexOf('<')

    if(pos === 0) {
      const [result, size] = parseStartTag(tpl)
      tpl = tpl.substring(size)
      
    
    } else if(pos > 0) {
      tpl = tpl.substring(pos)
      
    } 

    break
  }
}

function compileToFunction(tpl:string) {
  const ast = parseHtmlToAst(tpl.trim())

  const renderFunc = new Function(`${ast}`)

  return renderFunc
}


const render = compileToFunction(/* html */`
<div id="" style="width:100px" title="">
  <h1>{{ title }}</h1>

</div>
`)
